package me.helllp.dake.core.config;

import lombok.Getter;
import lombok.Setter;
import me.helllp.dake.common.security.AESEnum;
import me.helllp.dake.common.security.CryptoUtil;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;

import javax.annotation.PostConstruct;
import java.io.Serializable;
import java.util.Arrays;

@Configuration
@Getter
@Setter
@ConfigurationProperties(prefix="dake.crypto.config")
@PropertySource("classpath:dake_core.properties")
public class CryptoConfig {
    private String keyPart;

    private String algorithm;

    private Integer keyLength;

    private byte[] keyPartByte;

    private AESEnum aesEnum;

    @PostConstruct
    public void initData() throws Exception {
        keyPartByte = CryptoUtil.decode(keyPart);
        aesEnum = AESEnum.parser(algorithm);

        if (ObjectUtils.isEmpty(aesEnum)) {
            throw new Exception("AES算法参数配置有误");
        }

        if (!Arrays.asList(128,192,256).contains(keyLength)) {
            throw new Exception("参数中的秘钥长度有误，只能是128,192,256");
        }

        if (keyPartByte.length * 2 != (keyLength / 8)) {
            throw new Exception("秘钥配置长度有误！");
        }
    }
}
